<template>
  <div>
    <el-card>
      <h2>销售统计</h2>

      <!-- 日期选择 -->
      <el-form :inline="true" class="filter-form">
        <el-form-item label="开始日期">
          <el-date-picker
              v-model="startDate"
              type="date"
              placeholder="选择开始日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
              v-model="endDate"
              type="date"
              placeholder="选择结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchSalesData">统计</el-button>
        </el-form-item>
      </el-form>

      <!-- 总销售额展示 -->
      <div class="sales-summary">
        <el-statistic title="总销售额" :value="totalSales" :precision="2" prefix="¥"/>
      </div>

      <!-- 分客户销售额 -->
      <el-table :data="salesByCustomer" border stripe style="margin-top: 20px;">
        <el-table-column prop="cusName" label="客户名称"/>
        <el-table-column prop="sales" label="销售额"/>
      </el-table>

      <!-- 分商品销售额 -->
      <el-table :data="salesByProduct" border stripe style="margin-top: 20px;">
        <el-table-column prop="productName" label="商品名称"/>
        <el-table-column prop="sales" label="销售额"/>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import {ref} from "vue";
import {ElMessageBox} from "element-plus";
import {getTurnoverService} from "@/api/turnover.js";

// 日期选择
const startDate = ref(null);
const endDate = ref(null);

// 销售统计数据
const totalSales = ref(0);
const salesByCustomer = ref([]);
const salesByProduct = ref([]);

// 模拟从服务端获取统计数据
const fetchSalesData = async () => {
  if (!startDate.value || !endDate.value) {
    await ElMessageBox.alert("请选择开始日期和结束日期", "提示", {
      confirmButtonText: "确定",
      type: "warning",
    });
    return;
  }

  // 模拟 API 调用
  try {
    const response = await getTurnoverService(startDate.value, endDate.value)
    totalSales.value = response.data.data.totalSales;
    salesByCustomer.value = response.data.data.salesByCustomers;
    salesByProduct.value = response.data.data.salesByProducts;
  } catch (error) {
    await ElMessageBox.alert("获取销售统计数据失败", "提示", {
      confirmButtonText: "确定",
      type: "error",
    });
    console.error(error);
  }
};

</script>

<style scoped>
.filter-form {
  margin-bottom: 20px;
}

.sales-summary {
  margin-top: 20px;
}
</style>